package com.sirius.sipms.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.apache.log4j.Level;


public class Logger {

	private static  final String FQCN = Logger.class.getName();

	public static void debug(Object o) {
		getLogger().log(FQCN, Level.DEBUG, o, null);
	}

	public static void error(Object o) {
		getLogger().log(FQCN, Level.ERROR, o, null);
	}

	public static void fatal(Object o) {
		getLogger().log(FQCN, Level.FATAL, o, null);
	}

	/**
	 * 取得日志级别
	 * 
	 * @return
	 */
	public static Level getLevel() {
		return org.apache.log4j.Logger.getRootLogger().getLevel();
	}

	/**
	 * 取得日志级别
	 * 
	 * @return
	 */
	public static String getLevelToString() {
		return org.apache.log4j.Logger.getRootLogger().getLevel().toString();
	}
	
	private static org.apache.log4j.Logger getLogger() {
		String nameString = Thread.currentThread().getStackTrace()[3].getClassName();
		return org.apache.log4j.Logger.getLogger(nameString);
	}
	
	public static void info(Object o) {
		getLogger().log(FQCN, Level.INFO, o, null);
	}
	
	public static boolean isDebug() {
		return getLogger().isDebugEnabled();
	}
	public static boolean isError() {
		return getLogger().isEnabledFor(Level.ERROR);
	}

	public static boolean isFatal() {
		return getLogger().isEnabledFor(Level.FATAL);
	}

	public static boolean isInfo() {
		return getLogger().isInfoEnabled();
	}

	public static boolean isWarn() {
		return getLogger().isEnabledFor(Level.WARN);
	}

	//打印异常的堆栈信息
	public static void printStackTrace(Exception e){
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintStream stream = new PrintStream(outputStream);
        e.printStackTrace(stream);
        Logger.error(outputStream.toString());
        stream.close();
	}

	/**
	 * 设置系统日志级别
	 * 
	 * @param level
	 *            级别:debug,info,warn,error
	 * @return 0成功,1失败
	 */
	public static int setLevel(String level) {
		level = level.toUpperCase();
		if (level.equals("DEBUG")) {
			org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG);
			return 0;
		} else if (level.equals("INFO")) {
			org.apache.log4j.Logger.getRootLogger().setLevel(Level.INFO);
			return 0;
		} else if (level.equals("WARN")) {
			org.apache.log4j.Logger.getRootLogger().setLevel(Level.WARN);
			return 0;
		} else if (level.equals("ERROR")) {
			org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR);
			return 0;
		} else if (level.equals("FATAL")) {
			org.apache.log4j.Logger.getRootLogger().setLevel(Level.FATAL);
			return 0;
		}
		return -1;
	}

	public static void warning(Object o) {
		getLogger().log(FQCN, Level.WARN, o, null);
	}

}
